
angular.module('U9ImHd.controllers')

.controller('ConnectSettingCtrl', ['$scope', 'Connect', 'Device', 'InitService', 'Auth', 'Help', 'imanDialog',
    function ($scope, Connect, Device, InitService, Auth, Help, imanDialog) {
        $scope.data = {
            address: null,
            port: null,
            validSetting: false
        };

        $scope.settingChange = function () {
            if ($scope.data.validSetting) {
                $scope.data.validSetting = false;
            }
        };
        $scope.connectTest = function () {
            if ($scope.$$childHead.connectForm.$invalid) {
                imanDialog.toastBottom('请输入IP地址或端口');
                return;
            }
            imanDialog.showLoading();
            Connect.test($scope.data.address, $scope.data.port).then(function () {
                $scope.data.validSetting = true;
                imanDialog.hideLoading();
                imanDialog.toastBottom('连接设置测试成功');
            }, function () {
                $scope.data.validSetting = false;
                imanDialog.hideLoading();
                imanDialog.toastBottom('连接设置测试失败，请重新配置');
            });
        };
        $scope.setConnect = function () {
            Connect.set($scope.data.address, $scope.data.port).then(function () {
                return Device.updateLastRegister();
            }).finally(function () {
                Auth.setAuth(false);
                Help.goAsRoot('home');
            });
        };

        InitService.then(function () {
            $scope.data.address = Connect.get('address');
            $scope.data.port = Connect.get('port');
        });
    }
]);